import { getprofile, login } from '@/api/user'
import { setToken, getToken } from '@/utils/auth'
import { resetRouter } from '@/router'

const state = {
  // token: null
  token: getToken(),
  userInfo: {}
}
const mutations = {
  setToken(state, token) {
    state.token = token
    setToken(token)
  },
  setUserInfo(state, newUserInfo) {
    state.userInfo = newUserInfo
  }
}
const actions = {
  // 退出登录清空token
  logout(context) {
    context.commit('setToken', '')
    context.commit('setUserInfo', '')
    resetRouter()
  },
  // 首页获取用户资料发请求
  async getprofile(context) {
    const result = await getprofile()
    // console.log(result)
    context.commit('setUserInfo', result.data)
    // result.data.roles.points = []
    return result.data
  },
  // context上下文，传入参数
  async login(context, payload) {
    // console.log('从login.vue传回来的数据', payload)
    const result = await login(payload)
    // console.log(result)
    // todo: 调用登录接口
    const token = result.data
    // 返回一个token 123456
    context.commit('setToken', token)
  }
}
export default {
  namespaced: true, // 开启命名空间
  state,
  mutations,
  actions
}
